<template>
	<div class="trainAlternative train">
		<trainHeader name="选择车次" btn="确定" @btnClick="submit"></trainHeader>
		<div v-if="isShow">
			<!--主车次-->
			<div class="trainAlternative_box">
				<div class="trainAlternative_left">
					<div class="trainAlternative_title">备选车次 (多选几个车次，成功率更高)</div>
					<div class="trainAlternative_message">
						<div class="trainAlternative_city font_spill">
							<span>{{mainTrain.fromStation}}</span>
							<span class="trainAlternative_time active">{{mainTrain.fromTime}}</span>
						</div>
						<div class="trainAlternative_msg">
							<span>{{mainTrain.trainNo}}</span>
							<div>
								<img src="http://h5.kpcx179.com/wximages/train/daoda@2x.png" alt="" />
							</div>
							<span>{{mainTrain.runTimeSpan | runTime}}</span>
						</div>
						<div class="trainAlternative_city right font_spill">
							<span>{{mainTrain.toStation}}</span>
							<span class="trainAlternative_time">{{mainTrain.toTime}}</span>
						</div>
					</div>
				</div>
				<div class="trainAlternative_right"></div>
			</div>
			<div class="trainAlternative_zhan"></div>
			<!--备选-->
			<div class="trainAlternative_box" v-for="item,key in moveTrain" :class="{active:key}" @click="choose(key)">
				<div class="trainAlternative_left">
					<div v-if="!key" class="trainAlternative_title">多选车次</div>
					<div class="trainAlternative_message">
						<div class="trainAlternative_city font_spill">
							<span>{{item.fromStation}}</span>
							<span class="trainAlternative_time active">{{item.fromTime}}</span>
						</div>
						<div class="trainAlternative_msg">
							<span>{{item.trainNo}}</span>
							<div>
								<img src="http://h5.kpcx179.com/wximages/train/daoda@2x.png" alt="" />
							</div>
							<span>{{item.runTimeSpan | runTime}}</span>
						</div>
						<div class="trainAlternative_city right font_spill">
							<span>{{item.toStation}}</span>
							<span class="trainAlternative_time">{{item.toTime}}</span>
						</div>
					</div>
				</div>
				<div class="trainAlternative_right" :class="{active:!key}">
					<img src="http://h5.kpcx179.com/wximages/train/kuang-xuanzhong@2x.png" alt="" v-if="item.flag"/>
					<img src="http://h5.kpcx179.com/wximages/train/kuang-weixuan@2x.png" alt="" v-else/>
				</div>
			</div>
		</div>
	</div>
</template>
<style scoped>
	.trainAlternative {
		padding: 10px;
	}
	
	.trainAlternative_box {
		width: 100%;
		height: 195px;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 24px 35px;
		box-sizing: border-box;
		background: #fff;
		margin-bottom: 3px;
	}
	
	.trainAlternative_box.active {
		height: 160px;
	}
	
	.trainAlternative_left {
		width: 75%;
		height: 100%;
		font-size: 30px;
		color: #000000;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: flex-start;
	}
	
	.trainAlternative_title {
		margin-bottom: 28px;
		white-space : nowrap;
	}
	
	.trainAlternative_right {
		width: 25%;
		height: 100%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	
	.trainAlternative_right > img {
		width: 32px;
		height: 32px;
		margin-right: 30px;
	}
	
	.trainAlternative_right.active > img {
		margin-top: 50px;
	}
	
	.trainAlternative_message {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 25px;
		width: 100%;
		box-sizing: border-box;
	}
	
	.trainAlternative_city {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: flex-start;
		width: 30%;
	}
	
	.trainAlternative_city.right{
		align-items: flex-end;
	}
	
	.trainAlternative_time {
		margin-top: 20px;
		font-size: 32px;
	}
	
	.trainAlternative_time.active{
		color: #3bc3c2;
	}
	
	.trainAlternative_msg {
		width: 40%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 26px;
		color: #333333;
	}
	
	.trainAlternative_msg > div {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.trainAlternative_msg > div >img {
		width: 157px;
		height: 9px;
	}
	
	.trainAlternative_zhan {
		height: 20px;
	}
</style>
<script>
	import trainHeader from "../../../components/trainHeader";
	export default {
		name: "trainAlternative",
		data() { //数据
			return {
				msg:null,
				fillOrder:null,//订单填写页面变量
				mainTrain:null,//主车次
				moveTrain:null,//备选车次	
				isShow:false,
				num:0,//计数器
			}
		},
		mounted() {
			this.msg = this.$route.query;
			this.fillOrder = JSON.parse(JSON.stringify(this.$store.state.train.trainStore.fillOrder));
			this.num = this.fillOrder.alternative.train.length;
			this.getList();
		},
		created() {
			
		},
		methods: {
			submit(){ //确定
				var train = [];//选中的车次
				var seatArr = [];//坐席信息
				var fromDate = [];//发车时间
				this.moveTrain.forEach((val)=>{//获取选中的车次
					if (val.flag) { //选中的车次
						Object.keys(val.tickets).forEach(item => { //页面信息存储使用
							var message = {
								seatName: val.tickets[item].seatName, //坐席名称
					            price: val.tickets[item].price, //坐席价格
//					            price: val.tickets[item].lowestPrice, //坐席价格
					            lowestPrice: val.tickets[item].lowestPrice, //坐席最小价格
					            code: item, //英文code
					            trainNo:val.trainNo,//车次号
							};
							seatArr.push(message);
						}, this);
						train.push(val.trainNo);//车次号
						fromDate.push(val.fromDate);
					};
				},this);
//				console.log(seatArr,fromDate);
				this.getAlternativeSeat(seatArr);//处理备选坐席
				this.fillOrder.alternative.train = train;//选中的车次
				this.getFromDate(fromDate);//处理发车时间
				//更新上个页面变量
				var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
				trainStore.fillOrder = this.fillOrder;
				this.$store.commit('TRAINSTORE', trainStore);
				this.$router.go(-1);
			},
			getFromDate(fromDate){//处理发车时间
				var minTime = this.fillOrder.minTime.split(" ")[0];//最早预售时间
				var maxTime = this.fillOrder.maxDepartTime.split(" ")[0];//最晚抢票时间
				if (fromDate.length) { //有车
					fromDate.push(this.fillOrder.msg.startDate.time);
					var time = new Date().format('yyyy/MM/dd');
					fromDate.sort(function(a,b){//排序
						var timeOne = time + " " + a;
						var timeTwo = time + " " + b;
						return new Date(timeOne).getTime() - new Date(timeTwo).getTime();
					});
					minTime = minTime +" "+ fromDate[0] + ":00";
					maxTime = maxTime +" "+ fromDate[fromDate.length-1];
				} else { //没选
					minTime = minTime +" "+ this.fillOrder.msg.saleDateTime.split(" ")[1];
					maxTime = maxTime +" "+ this.fillOrder.msg.startDate.time;
				};
//				maxTime = new Date(new Date(maxTime.replace(/-/g,"/")).getTime() - 3*60*60*1000).format("yyyy-MM-dd hh:mm");
				this.fillOrder.minTime = minTime;//最小预售时间
				this.fillOrder.maxDepartTime = maxTime;//最晚发车时间
			},
			getAlternativeSeat(seatArr){ //处理备选坐席
				var alternative = this.fillOrder.alternative.seat;//坐席
				seatArr.push(...alternative.mainSeat);//所有坐席
				var mainSeatArr = [];//与主坐席相同的坐席
				var elseSeatArr = [];//其他坐席
				seatArr.forEach((val)=>{
					(val.seatName == alternative.mainSeatMessage.seatName) ? mainSeatArr.push(val) : elseSeatArr.push(val);
				});
				alternative.maxPriceSeat = this.getMaxPriceSeat(mainSeatArr,alternative.mainSeatMessage);//筛选最大的备选坐席
				alternative.all = this.getRepeat(elseSeatArr);//坐席去重
				alternative.choose.length = 0;//选中坐席清空
				alternative.allSeat = seatArr;//所有的坐席记录
				this.fillOrder.coupon.name = "";//优惠券清空
				this.fillOrder.coupon.price = 0;
				this.fillOrder.coupon.id = "";
			},
			getRepeat(arr){ //坐席去重   //处理座位相同票价不同的情况	
			    arr.forEach((val,key)=>{//添加一个ID
			        arr[key].id = key;
			    });
			    var mgs = [];//存放要删除的id
			    for (var i = 0; i < arr.length; i++) {
			      for (var j = i + 1; j < arr.length; j++) {
			        (arr[i].seatName == arr[j].seatName) && ((arr[i].price > arr[j].price) ? mgs.push(arr[j].id) : mgs.push(arr[i].id));
			      };
			    };
			    mgs.forEach((val)=>{//删除指定
			      arr.forEach((item,key) => {
			        (item.id == val) && (arr.splice(key, 1));
			      });
			    });
			    return arr;
			},
			getMaxPriceSeat(seatArr,seat){//筛选最大的备选
				var max = seat;
				seatArr.forEach((val,index)=>{
					(seatArr[index].price > max.price) && (max = seatArr[index]);
				});
				return max;
			},
			getList(){ //获取车次列表
				this.$loading.show();
				var param = {
					fromStation: encodeURI(this.msg.formCity),
				    toStation: encodeURI(this.msg.toCity),
				    ticketType: 1, // 1正常票  2学生票  默认1
				    trainDate: this.msg.departureDate.replace(/-/g, ''),
				};
				this.$http.post(this.$baseUrl.baseurl + "tctrain/train/train", param).then((res) => {
					this.$loading.hide();
					if(res.data.Code == "0") { //验证成功下单
//						console.log(res.data);
						this.fillOrder.queryKey = res.data.Result.queryKey;//存请求key
						var index = null;//主车次的index
						Array.isArray(res.data.Result.trains) && res.data.Result.trains.forEach((val,key)=>{//筛选备选车次
							val.flag = false;//选中标识，默认都不选中
							(val.trainNo == this.msg.trainNo) && (index = key);
            				res.data.Result.trains[key].fromDate = val.fromTime;//获取发车时间
            				(this.fillOrder) && this.fillOrder.alternative.train.forEach((item)=>{ //筛选中
            					(item == val.trainNo) && (val.flag = true);
            				});
						},this);
						this.mainTrain = (index == null) ? {} : res.data.Result.trains.splice(index, 1)[0]; //获取主车次
						this.moveTrain = res.data.Result.trains;//备选车次
						this.isShow = true;
//						console.log(this.mainTrain,this.moveTrain);
					} else {
						this.$toast(res.data.msg, {
							durtaion: 200,
							location: 'center',
						});
					};
				}).catch((err) => {
					this.$loading.hide();
					console.log(err);
				});
			},
			choose(key){ //备选车次选中和反选
				this.moveTrain[key].flag ? ((this.moveTrain[key].flag = false) || (this.num --)) : (this.num > 6) ? this.$toast("最多可以选择7个备选车次哦", {
					durtaion: 200,
					location: 'center',
				}) : ((this.moveTrain[key].flag = true) && (this.num ++));
			},
		},
		components: {
			trainHeader
		},
		filters: { //过滤
			runTime(runTime) {
				return(Math.floor(runTime / 60) > 0) ? (Math.floor(runTime / 60) + '小时' + (runTime % 60) + '分钟') : (runTime + "分钟");
			},
		},
	};
</script>